<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 15:02:24
 * Info: 权限节点控制器
 */

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\model\AuthRule as AuthRuleModel;
use think\facade\Cache;
use think\facade\View;
use app\common\service\admin\CacheClearService;

class AuthRule extends Base
{

    /**
     * 权限列表
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = AuthRuleModel::where(['delete_time' => 0])->order("sort asc,id asc")->select();
            $this->success('ok', $list);
        }

        return View::fetch();
    }

    /**
     * 添加权限
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['pid'])) {
                $param['pid'] = 0;
            }
            if (empty($param['title'])) {
                $this->error("权限名称不能为空");
            }
            if (empty($param['node'])) {
                $this->error("权限地址不能为空");
            }
            if (strpos($param['node'], "/") === 0) {
                $param['node'] = substr($param['node'], 1);
            }

            $param['icon'] = ! empty($param['icon']) ? (string)$param['icon'] : 'layui-icon-circle-dot';
            //查询是否已存在
            $findData = AuthRuleModel::where('node', $param['node'])->find();
            if ( ! empty($findData)) {
                $this->error("该权限地址已存在");
            }
            AuthRuleModel::create($param);
            $adminId = cmf_get_admin_id();
            //清除缓存
            CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
            //清除后台菜单缓存
            CacheClearService::clearMenu($adminId);

            //写入语言包：
            $langList = config('lang.allow_lang_list');
            foreach ($langList as $l) {
                $langPath    = __DIR__."/../lang/".$l."/admin_menu.php";
                $insertTitle = [];

                // 根据语言类型设置键值对
                switch ($l) {
                    case 'zh-cn':
                        if ( ! empty($param['title'])) {
                            $insertTitle = [$param['title_en'] => $param['title']];
                        }
                        break;
                    case 'zh-hk':
                        if ( ! empty($param['title_hk'])) {
                            $insertTitle = [$param['title_en'] => $param['title_hk']];
                        }
                        break;
                    case 'en-us':
                        if ( ! empty($param['title_en'])) {
                            $insertTitle = [$param['title_en'] => $param['title_en']];
                        }
                        break;
                    default:
                        // 默认处理
                        if ( ! empty($param['title'])) {
                            $insertTitle = [$param['title_en'] => $param['title']];
                        }
                        break;
                }

                // 如果有数据，写入语言文件
                if ( ! empty($insertTitle)) {
                    $this->writeLangFile($langPath, $insertTitle);
                }
            }

            $this->success('保存成功');

        }
        $id      = (int)input('get.id');
        $pidList = AuthRuleModel::getPidMenuList();

        View::assign('id', $id);
        View::assign('pidList', $pidList);

        return View::fetch();
    }

    /**
     * 编辑权限
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['pid'])) {
                $param['pid'] = 0;
            }
            if (empty($param['id'])) {
                $this->error('参数错误');
            }
            if (empty($param['title'])) {
                $this->error("权限名称不能为空");
            }
            if (empty($param['node'])) {
                $this->error("权限地址不能为空");
            }
            if (strpos($param['node'], "/") === 0) {
                $param['node'] = substr($param['node'], 1);
            }

            $param['icon'] = ! empty($param['icon']) ? (string)$param['icon'] : 'layui-icon-circle-dot';
            //查询是否已存在
            $findData = AuthRuleModel::where('node', $param['node'])->where('id', '<>', $param['id'])->find();
            if ( ! empty($findData)) {
                $this->error("该权限地址已存在");
            }
            AuthRuleModel::update($param, ['id' => $param['id']]);
            $adminId = cmf_get_admin_id();
            //清除缓存
            CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
            //清除后台菜单缓存
            CacheClearService::clearMenu($adminId);

            //写入语言包：
            $langList = config('lang.allow_lang_list');
            foreach ($langList as $l) {
                $langPath    = __DIR__."/../lang/".$l."/admin_menu.php";
                $insertTitle = [];

                // 根据语言类型设置键值对
                switch ($l) {
                    case 'zh-cn':
                        if ( ! empty($param['title'])) {
                            $insertTitle = [$param['title_en'] => $param['title']];
                        }
                        break;
                    case 'zh-hk':
                        if ( ! empty($param['title_hk'])) {
                            $insertTitle = [$param['title_en'] => $param['title_hk']];
                        }
                        break;
                    case 'en-us':
                        if ( ! empty($param['title_en'])) {
                            $insertTitle = [$param['title_en'] => $param['title_en']];
                        }
                        break;
                    default:
                        // 默认处理
                        if ( ! empty($param['title'])) {
                            $insertTitle = [$param['title_en'] => $param['title']];
                        }
                        break;
                }

                // 如果有数据，写入语言文件
                if ( ! empty($insertTitle)) {
                    $this->writeLangFile($langPath, $insertTitle);
                }
            }

            $this->success('保存成功');
        }
        $id   = (int)input('get.id');
        $data = AuthRuleModel::where(['id' => $id])->find();
        if (empty($data)) {
            $this->error('获取数据失败');
        }
        $pidList = AuthRuleModel::getPidMenuList();

        View::assign('id', $id);
        View::assign('data', $data);
        View::assign('pidList', $pidList);

        return View::fetch();
    }

    /**
     * 删除权限
     * @return \support\Response|\think\response\Json|\think\response\View
     */
    public function delete()
    {
        $id = (int)input('get.id');
        if (empty($id)) {
            $this->error("参数错误");
        }
        //查询数据
        $findData = AuthRuleModel::where(['id' => $id])->find();
        if (empty($findData)) {
            $this->error("获取数据失败，该数据不存在！");
        }
        //查询子级是否存在
        $findPidData = AuthRuleModel::where(['pid' => $id])->count();
        if ($findPidData > 0) {
            $this->error("请先删除子级后再操作！");
        }
        AuthRuleModel::destroy(['id' => $id]);
        $adminId = cmf_get_admin_id();
        //清除缓存
        CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
        //清除后台菜单缓存
        CacheClearService::clearMenu($adminId);

        // 删除语言包：
        $langList = config('lang.allow_lang_list');
        foreach ($langList as $l) {
            $langPath    = __DIR__."/../lang/".$l."/admin_menu.php";
            $insertTitle = [];
            // 如果有数据，写入语言文件
            if ( ! empty($findData['title_en'])) {
                $this->writeLangFile($langPath, $insertTitle, $findData['title_en']);
            }
        }

        $this->success("删除成功");
    }

    /**
     * 列表页的操作
     * @return void
     */
    public function modify()
    {
        if ($this->request->isAjax()) {
            $id = (int)input('id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            $field = input('field');
            $val   = input('val');
            AuthRuleModel::update([$field => $val], ['id' => $id]);
            //清除缓存
            $adminId = cmf_get_admin_id();
            CacheClearService::clearAdminMenu('cacheAdminMenuId'.$adminId);
            //清除后台菜单缓存
            CacheClearService::clearMenu($adminId);

            $this->success('操作成功');
        }

    }

    /**
     * 写入语言文件
     *
     * @param string $filePath 文件路径
     * @param array  $data     语言数据
     */
    protected function writeLangFile($filePath, $data = [], $deleteKeys = [])
    {
        // 如果文件不存在，创建文件
        if ( ! file_exists($filePath)) {
            file_put_contents($filePath, "<?php\n\nreturn [];");
        }

        // 读取现有数据
        $existingData = include $filePath;
        $existingData = $existingData['auth_menu'] ?? [];

        // 删除指定键
        foreach ($deleteKeys as $key) {
            if (isset($existingData[$key])) {
                unset($existingData[$key]);
            }
        }

        // 合并新数据
        $existingData = array_merge($existingData, $data);
        $existingData = ['auth_menu' => $existingData];

        $content = "<?php\n\nreturn ".var_export($existingData, true).";";
        file_put_contents($filePath, $content);
    }

}
